const http=require('http');
const request=require('request');
const hostname='localhost';

const apiPort=8020;
const img1Port=8021;
const img2Port=8020;

const apiServer=http.createServer((req,res)=>{
    const url="http://api.douban.com/v2/movie/top250"+req.url;
    const options={
        url:url
    };

    function callback(error,response,body){
        if(!error&&response.statusCode===200){
            res.setHeader('Content-type','text/plain;charset=UTF-8');
            res.setHeader('Access-Control-Allow-Origin','*');
            res.end(body);
        }
    }
    request.get(options,callback);
});

//listen 8020
apiServer.listen(apiPort,hostname,()=>{
    console.log('接口运行代理在8020');
});

//create a pic proxy(8021)
const img1Server=http.createServer((req,res)=>{
    const url=req.url.split('/img/')[1];
    const options={
        url:url,
        encoding:null
    };

    function callback(error,response,body){
        if(!error&&response.statusCode===200){
            const contentType=response.headers['content-type'];
            res.setHeader('Content-Type', contentType);
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.end(body);
        }
    }
    request.get(options,callback);
});

img1Server.listen(img1Port,hostname,()=>{
    console.log('图片代理在8021')
})